package com.hulk.dryad.manage.boot.injector.impl;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.hulk.dryad.manage.boot.injector.SuperService;
import com.hulk.dryad.persistence.injector.basic.BasicSqlMethod;
import com.hulk.dryad.persistence.injector.basic.mapper.SuperMapper;

import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * Service 实现类（ 泛型：M 是 mapper 对象，T 是实体 ， PK 是主键泛型 ）
 *
 * @author hulk
 */
public class SuperServiceImpl<M extends SuperMapper<T>, T> extends ServiceImpl<M, T> implements SuperService<T> {

	@Override
	public boolean saveIgnore(T entity) {
		return SqlHelper.retBool(baseMapper.insertIgnore(entity));
	}

	@Override
	public boolean saveReplace(T entity) {
		return SqlHelper.retBool(baseMapper.replace(entity));
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean saveIgnoreBatch(Collection<T> entityList, int batchSize) {
		return saveBatch(entityList, batchSize, BasicSqlMethod.INSERT_IGNORE_ONE);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean saveReplaceBatch(Collection<T> entityList, int batchSize) {
		return saveBatch(entityList, batchSize, BasicSqlMethod.REPLACE_ONE);
	}

	private boolean saveBatch(Collection<T> entityList, int batchSize, BasicSqlMethod sqlMethod) {
		String sqlStatement = baseSqlStatement(sqlMethod);
		executeBatch(entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));
		return true;
	}

	/**
	 * 获取 SqlStatement
	 *
	 * @param sqlMethod ignore
	 * @return sql
	 */
	protected String baseSqlStatement(BasicSqlMethod sqlMethod) {
		return mapperClass.getName() + StringPool.DOT + sqlMethod.getMethod();
	}
}
